ATOM SaaS Billing & Subscription Management
This module handles the SaaS billing logic with Stripe integration, subscription management, and storage tracking.
🏗️ Architecture
Components:
- **Subscription Service**: Stripe integration for billing
- **Storage Tracker**: S3 usage monitoring per tenant
- **Limit Enforcer**: Middleware to enforce plan limits
- **Billing Engine**: Recurring charges and invoicing
💳 Pricing Plans
Free Tier
- Price: $0/month
- Storage: 5MB
- Users: 3
- Features: Basic AI, limited workflows
- API Calls: 1,000/month
Pro Tier
- Price: $29/month
- Storage: 100MB
- Users: 10
- Features: Full AI, unlimited workflows, advanced integrations
- API Calls: 10,000/month
Enterprise
- Price: $99+/month
- Storage: 1GB+
- Users: Unlimited
- Features: Everything + priority support, custom features
- API Calls: Unlimited
📊 Storage Calculation
Storage Types Tracked:
- Document uploads
- AI conversation attachments
- Workflow exports
- User profile images
- Backup files
Real-time Tracking:
# Track S3 usage per tenant
def track_storage_usage(tenant_id, file_size, file_type='upload'):
# Update database
update_storage_usage(tenant_id, file_size, file_type)
# Check limits
if exceeds_limit(tenant_id):
raise StorageLimitExceeded()
# Log to analytics
analytics.track('storage_used', {
'tenant_id': tenant_id,
'size': file_size,
'type': file_type
})🔄 Subscription Lifecycle
New Tenant Flow:
- Create tenant account (free tier)
- Verify email address
- Set up initial workspace
- Offer upgrade to paid plans
Upgrade Flow:
- User selects plan
- Redirect to Stripe Checkout
- Process payment
- Update tenant plan in database
- Grant additional features
- Send confirmation email
Downgrade Flow:
- User requests downgrade
- Pro-rate current subscription
- Schedule end of current period
- At period end: remove premium features
- Enforce new storage limits
- Notify user of changes
🛡️ Limit Enforcement
Storage Limits:
- **Real-time check**: Before file upload
- **Background job**: Recalculate S3 usage hourly
- **Buffer**: 5% overage allowed with warning
- **Grace period**: 7 days after limit exceeded
API Rate Limits:
- **Free tier**: 100 calls/hour
- **Pro tier**: 1,000 calls/hour
- **Enterprise**: Unlimited
Feature Limits:
# Middleware to check feature access
@app.before_request
def check_feature_access():
tenant_id = get_current_tenant()
feature = request.endpoint
if not feature_enabled(tenant_id, feature):
return jsonify({'error': 'Feature not available in your plan'}), 403📈 Revenue Metrics
Key Metrics Tracked:
- **MRR**: Monthly Recurring Revenue
- **ARR**: Annual Recurring Revenue
- **Churn Rate**: Customer attrition percentage
- **LTV**: Customer Lifetime Value
- **CAC**: Customer Acquisition Cost
Dashboard Features:
- Real-time revenue tracking
- Customer growth metrics
- Plan distribution analytics
- Revenue forecasts
🔧 Integration Points
Stripe Webhooks:
customer.subscription.created- New subscriptioncustomer.subscription.updated- Plan changescustomer.subscription.deleted- Cancellationsinvoice.payment_succeeded- Successful paymentsinvoice.payment_failed- Payment failures
S3 Storage Events:
- ObjectCreated events for tracking uploads
- ObjectRemoved events for storage cleanup
- Lifecycle policies for cost optimization
📝 Usage Examples
Create Subscription:
def create_subscription(tenant_id, plan_id):
customer = stripe.Customer.create(
email=get_tenant_email(tenant_id),
metadata={'tenant_id': tenant_id}
)
subscription = stripe.Subscription.create(
customer=customer.id,
items=[{'price': plan_id}],
payment_behavior='default_incomplete',
expand=['latest_invoice.payment_intent'],
metadata={'tenant_id': tenant_id}
)
return subscriptionCheck Storage Limit:
def check_storage_limit(tenant_id, upload_size):
tenant = get_tenant(tenant_id)
current_usage = get_storage_usage(tenant_id)
if (current_usage + upload_size) > tenant.storage_limit_mb * 1024 * 1024:
raise StorageLimitExceeded(
current=current_usage,
limit=tenant.storage_limit_mb,
upload_size=upload_size
)🎯 Best Practices
- **Transparent Pricing**: Clear limits and overage charges
- **Gradual Upgrades**: Easy upgrade path with minimal friction
- **Graceful Degradation**: Don't immediately block users on limit breaches
- **Usage Analytics**: Help customers understand their usage patterns
- **Automated Billing**: Reduce manual intervention in billing process
- **Customer Communication**: Notify users before limits are reached
- **Data Retention**: Clear policies for data after downgrade/cancellation
🚨 Edge Cases
Payment Failures:
- Retry logic with exponential backoff
- Grace period for failed payments
- Feature reduction before full suspension
Storage Overages:
- Temporary overage allowance (5%)
- Warning emails at 80%, 95%, 100% usage
- Soft limits vs hard limits enforcement